package com.kehao.leetcode.middle.array;

import org.junit.Test;

import java.util.*;



public class ThreeSumSolution {

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        int left,right;
        for (int i = 0; i < nums.length-2; i++) {
            if(nums[i]>0) break;
            if(i>0&&nums[i]==nums[i-1]) continue;
            left=i+1;
            right=nums.length-1;
            while (left<right){
                if(nums[i]+nums[left]+nums[right]==0){
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    result.add(list);
                    left++;
                    right--;
                    while(nums[left]==nums[left-1]&&left<right){
                        left++;
                    }
                    while(nums[right]==nums[right+1]&&left<right){
                       right--;
                    }
                }else if(nums[i]+nums[left]+nums[right]>0){
                    right--;
                }else {
                    left++;
                }
            }
        }


        return result;
    }

    @Test
    public void test01(){
        int [] nums = new int[]{-1,0,1,2,-1,-4};
        System.out.println(threeSum(nums));
    }
}
